import { join } from 'path'

import { EggAppConfig, EggAppInfo, PowerPartial } from 'egg'
import { config } from 'dotenv'
import * as redisStore from 'cache-manager-ioredis'

export type DefaultConfig = PowerPartial<EggAppConfig>

const envConfig: any = config({
  path: join(__dirname, '../../../.env')
})?.parsed

export default (appInfo: EggAppInfo) => {
  const config = {} as DefaultConfig

  // use for cookie sign key, should change to your own and keep security
  config.keys = appInfo?.name + '_1624360047360_744'

  config.security = {
    csrf: {
      enable: false
    }
  }

  // add your config here
  config.middleware = ['jwtAuthMiddleware', 'proxyMiddleware']

  config.midwayFeature = {
    // true 代表使用 midway logger
    // false 或者为空代表使用 egg-logger
    replaceEggLogger: true
  }

  config.logger = {
    dir: join(__dirname, '../../../logs/api')
  }

  if (process.env.NODE_ENV !== 'production') {
    config.orm = {
      type: 'postgres',
      host: envConfig.REMOTE_URL,
      port: envConfig.POSTGRES_PORT,
      username: 'postgres',
      password: envConfig.POSTGRES_PASSWORD,
      database: envConfig.POSTGRES_DATABASE,
      synchronize: true,
      logging: true
    }
  }

  config.proxy = {
    ['/' + envConfig.MINIO_BUCKET]: {
      target: `http://${envConfig.REMOTE_URL}:` + envConfig.MINIO_PORT,
      xfwd: true,
      logLevel: 'silent'
    },
    '/unsafe': {
      target: `http://${envConfig.REMOTE_URL}:` + envConfig.THUMBOR_PORT,
      xfwd: true,
      logLevel: 'silent'
    },
    '/v1/graphql': {
      target: `http://${envConfig.REMOTE_URL}:` + envConfig.HASURA_PORT,
      xfwd: true,
      logLevel: 'error',
      onProxyReq(proxyReq, req, res, state) {
        if (state.role) {
          proxyReq.setHeader('x-hasura-role', state.role)
        }
      }
    },
    '/gf': {
      target: `http://${envConfig.REMOTE_URL}:` + envConfig.GRAFANA_PORT,
      pathRewrite: { '^/gf' : '' },
      ws: true,
      xfwd: true,
      logLevel: 'error'
    },
    // office
    '/web-apps': {
      target: `http://${envConfig.REMOTE_URL}:` + envConfig.OFFICE_PORT,
      logLevel: 'silent'
    },
    '/7.0.1': {
      target: `http://${envConfig.REMOTE_URL}:` + envConfig.OFFICE_PORT,
      logLevel: 'silent'
    },
    '/sdkjs': {
      target: `http://${envConfig.REMOTE_URL}:` + envConfig.OFFICE_PORT,
      xfwd: true,
      changeOrigin: true,
      logLevel: 'silent'
    },
    '/cache': {
      target: `http://${envConfig.REMOTE_URL}:` + envConfig.OFFICE_PORT,
      xfwd: true,
      changeOrigin: true,
      logLevel: 'silent'
    },
    '/doc': {
      target: `http://${envConfig.REMOTE_URL}:` + envConfig.OFFICE_PORT,
      xfwd: true,
      changeOrigin: true,
      logLevel: 'silent'
    }
  }

  config.graphql = {
    HASURA_ENDPOINT: `http://${envConfig.REMOTE_URL}:` + envConfig.HASURA_PORT + '/v1/graphql',
    HASURA_GRAPHQL_ADMIN_SECRET: envConfig.HASURA_GRAPHQL_ADMIN_SECRET
  }

  config.jwt = {
    issuer: 'inecho.com',
    expiresIn: '60m',
    refreshExpiresIn: '7d',
    keyPath: join(__dirname, '../../../pem/private.pem')
  }

  config.minio = {
    endPoint: envConfig.REMOTE_URL,
    port: Number(envConfig.MINIO_PORT),
    accessKey: envConfig.MINIO_ACCESS_KEY,
    secretKey: envConfig.MINIO_SECRET_KEY,
    bucketName: envConfig.MINIO_BUCKET
  }

  config.multipart = {
    fileSize: '20mb',
    mode: 'stream',
    whitelist: [
      // image
      '.png', '.jpg', '.jpeg', '.webp',
      // office
      '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.pdf',
      // mac
      '.pages', '.numbers',
      // video
      '.mp4'
    ]
  }

  config.email = {
    host: 'smtp.exmail.qq.com',
    port: 465,
    auth: {
      user: '123',
      pass: '123'
    }
  }

  config.view = {
    mapping: {
      '.ejs': 'ejs'
    }
  }

  config.office = {
    fileHost: `http://host.docker.internal:${envConfig.MINIO_PORT}`,
    host: `http://${envConfig.REMOTE_URL}:` + envConfig.OFFICE_PORT
  }

  config.sms = {
    accessKeyId: 'XXXX',
    accessKeySecret: 'XXXX',
    // aliyun
    SignName: 'XXXX',
    TemplateCode: 'XXXX'
  }

  config.wechat = {
    appid: envConfig.WECHAT_APPID,
    secret: envConfig.WECHAT_SECRET
  }

  config.cache = {
    // store: 'memory',
    // options: {
    //   max: 100,
    //   ttl: 10,
    // }
    store: redisStore,
    options: {
      host: envConfig.REMOTE_URL,
      port: Number(envConfig.REDIS_PORT),
      password: envConfig.REDIS_PASSWORD,
      db: 0,
      keyPrefix: 'cache:',
      ttl: 100
    }
  }

  config.taskConfig = {
    redis: {
      host: envConfig.REMOTE_URL,
      port: Number(envConfig.REDIS_PORT),
      password: envConfig.REDIS_PASSWORD
    },
    prefix: 'task:',
    defaultJobOptions: {
      repeat: {
        tz: 'Asia/Shanghai'
      }
    }
  }

  return config
}
